import { reactive, toRefs } from 'vue';
import IWebsocket from '../chatWS'
import { Chat } from '@/store/chat';
import pinia from '@/store/index';
import { Local } from "@/utils/storage";

const chat = Chat(pinia);

const state_data: any = reactive({
  Input: null,
  per_page: 150,
  page: 1,
  keywordArr: [], //关键词列表
});

const usechatHooks = (state?: any) => {
  const getchatId = () => {
    if (state.deviceID > state.todeviceid) {
      return state.deviceID + '-' + state.todeviceid; //大的在前小的在后
    } else {
      return state.todeviceid + '-' + state.deviceID; //大的在前小的在后
    }
  };
  // 解析消息体
  const decodeContent = (data: any, name: string) => {
    let MessageOutputeItem = state.root.lookupType(name)
    const buffer1 = new Uint8Array(data);
    const decodedMessage2 = MessageOutputeItem.decode(buffer1);

    return MessageOutputeItem.toObject(decodedMessage2);
  }
  // 编码发送参数
  const encodeParams = (params: any, name: string) => {
    let item = state.root.lookupType(name)
    const errMsg = item.verify(params);
    if (errMsg) throw new Error(errMsg);
    const message = item.create(params);
    const buffer = item.encode(message).finish();
    return buffer;
  }
  const encodeInput = (type: any, request_id: any, data: any) => {
    state_data.Input = state.root.lookupType('Input');
    // Build payload object
    const payload = {
      type: type,
      requestid: request_id,
      data: data,
    };
    // Verify payload
    const errMsg = state_data.Input.verify(payload);
    if (errMsg) throw new Error(errMsg);
    // Create message
    const message = state_data.Input.create(payload);
    // Encode message
    const buffer = state_data.Input.encode(message).finish();
    return buffer;
  };
  // 公共发送方法  type:类型    payload 参数  Req请求类型
  const wsReqSend = (type: any, payload: any, Req: any) => {
    state.requestid++;
    const requestid = state.requestid;
    //编码消息体
    const decodedata = encodeParams(payload, Req);
    const encodedRequest = encodeInput(type, requestid, decodedata);
    IWebsocket.sendMessageHandler(encodedRequest);
  };
  //  同步历史数据
  const synchistorymsg = () => {
    const type = 8;
    var payload = {
      chatid: getchatId(),
      perpage: state_data.per_page,
      page: 1,
    };
    wsReqSend(type, payload, 'SyncHistoryInput');
  };

  // 获取快捷语--分类列表
  const getShortcutCatelist = () => {
    const type = 23; //
    const payload = {
      deviceid: state.deviceID,
      page: 1,
      pagesize: 200,
    };
    wsReqSend(type, payload, 'QuickPhrasesCListListReq');
  };
  // 接收快捷语--分类列表
  const getShortcutCateMsg = (decodeobj1: any) => {
    if (decodeobj1.data) {
      const decodeobj00 = decodeContent(decodeobj1.data, 'QuickPhrasesCListRsp');
      state.shortCutTyptList = decodeobj00.quickphrasec;
      console.log('快捷语分类列表', state.shortCutTyptList);
    }
  };
  // 获取快捷语列表
  const getShortcutlist = () => {
    const type = 19; //
    const payload = {
      deviceid: state.deviceID,
      page: 1,
      pagesize: 200,
    };
    wsReqSend(type, payload, 'QuickPhrasesListReq');
  };
  // 接收快捷语列表
  const getShortcutMsg = (decodeobj1: any) => {
    if (decodeobj1.data) {
      const decodeobj00 = decodeContent(decodeobj1.data, 'QuickPhrasesListRsp');
      state.quickPhrasesList = decodeobj00.quickphrase.sort((_: any, b: any) => b.istop === 1 ? 1 : -1);
      console.log('快捷语列表', state.quickPhrasesList);
      //   快捷语自动回复状态保存
      let arr = state.quickPhrasesList
      let bol = false
      let text = ''
      arr.map((item: any) => {
        if (item.isautorsp == 1) {
          bol = true
          text = item.content
        }
      })
      chat.setAutoreply(bol)
      chat.setAutoreplyText(text)
    }
  };

  // 消息同步，已读
  const alreadread = () => {
    const type = 27; // item已读
    var payload = {
      deviceid: state.deviceID,
      chatid: getchatId(),
    }
    wsReqSend(type, payload, 'ReadChatItemReq');
  }

  // 获取关键词列表
  const keywordList = () => {
    const type = 28; // 查询用户
    var payload = {
      deviceid: state.deviceID,
    };
    wsReqSend(type, payload, 'KwlistReq');
  };

  // 获取关键词列表
  const getkeywordList = (decodeobj1: any) => {
    const decodeobj00 = decodeContent(decodeobj1.data, 'KwlistReqRsp');
    state_data.keywordArr = decodeobj00.words?.map((item: any) => item.word) || [];
    Local.set('keywordArr', state_data.keywordArr)
    console.log('违禁词', state_data.keywordArr)
  };
  //处理聊天数据表情
  const initMessage = (text: string) => {
    const EMOJI_REMOTE_SRC = 'https://cdn.jsdelivr.net/npm/emoji-datasource-apple@6.0.1/img/apple/64';
    const emojiCache: { [key: string]: string } = {};
    function replaceWithEmojiImages(text: string) {
      const regex = /\/:(.*?):\//g;
      if (text) {
        return text.replace(regex, (match) => {
          const value = match.slice(2, -2);
          if (!emojiCache[value]) {
            const imgSrc = `${EMOJI_REMOTE_SRC}/${value}.png`;
            emojiCache[value] = `<img data-code="${value}" src="${imgSrc}" width="20" height="20" class="emoji-img"/>`;
          }
          return emojiCache[value];
        });
      }
    }
    const outputText = replaceWithEmojiImages(text);
    return outputText;
  };
  return {
    ...toRefs(state_data),
    synchistorymsg,
    encodeInput,
    encodeParams,
    decodeContent,

    getShortcutCatelist,
    getShortcutCateMsg,
    getShortcutlist,
    getShortcutMsg,
    alreadread,
    keywordList,
    getkeywordList,
    initMessage,
  };
};
export default usechatHooks;
